<?php namespace Admin\Controller;
//商品列表控制器
class GoodsListController extends CommonController
{
	private $model,$goodsAttr,$typeAttr;
	public function __auto(){
		$this->model=new \Common\Model\GoodsList;
		$this->goodsAttr=new \Common\Model\GoodsAttr;
		$this->typeAttr=new \Common\Model\TypeAttr;
	}
	//显示主列表
	public function index(){
		$gid=Q('get.gid',0,'intval');
		// P($gid);die;
		//获得表头字段名所需要的数据
		$data=$this->goodsAttr
			->join('typeattr','type_attr_taid','=','taid')
			->where("goods_gid={$gid} AND attr_type=1")
			->groupby('taid')
			->get();
		//添加货品时下拉菜单所选择的内容一定是在商品属性表中获得的
		foreach($data as $k=>$v){
			$data[$k]['value']=$this->goodsAttr->where("type_attr_taid={$v['taid']} AND goods_gid={$gid}")->get();
		}
		// P($data);
		//显示有货以后列表
		$listData=$this->model->where("goods_gid={$gid}")->get();
		// P($listData);
		foreach($listData as $k=>$v){
			$vv=explode(',',$v['groupid']);
			foreach($vv as $value){
				$listData[$k]['value'][]=$this->goodsAttr->where("gaid =$value")->find();
			}
			
		}
//		P($listData);
		View::with('listData',$listData);
		View::with('data',$data);
		View::make();
	}
	//添加货品列表
	public function add(){
		if(IS_POST){
			if($this->model->store()){
				View::success("添加成功");
			}
		}
		View::error($this->model->getError());
	}
	//编辑货品列表
	public function edit(){
		if(IS_POST){
			$gid=Q('post.goods_gid',0,'intval');
			// P($gid);die;
			if($this->model->edit()){
				View::success("编辑成功",U('GoodsList/index',array('gid'=>"{$gid}")));
			}
			View::error($this->model->getError());
		}
		//获取旧数据
		$glid=Q('get.glid',0,'intval');
		$data=$this->model->where("glid={$glid}")->find();
		$gid=$data['goods_gid'];
		$value=$this->goodsAttr
			 ->join('typeattr','type_attr_taid','=','taid')
			 ->where("goods_gid={$gid} AND attr_type=1")
			 ->groupby('taid')
			 ->get();
        //可选的商品属性必须在商品属性列表中能找到
		$da=explode(',',$data['groupid']);
		foreach($value as $k=>$v){
			$value[$k]['value']=$this->goodsAttr->where("type_attr_taid={$v['taid']} AND goods_gid={$gid}")->get();
			$value[$k]['zhi']=$da[$k];
		}
		
//		P($da);
		// P($value);die;
		View::with('data',$data);
		View::with('value',$value);
		View::make();
	}
	//删除货品列表
	public function del(){
		$data=Q('get.');
		// P(Q('get.'));die;
		$glid=$data['glid'];
		$gid=$data['gid'];
		$this->model->where("glid={$glid}")->delete();
		View::success("删除成功",U('index',array('gid'=>"{$gid}")));
	}
}